package top.frsf.mqtt.handler.strategy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.MqttConnectMessage;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.frsf.mqtt.handler.strategy.abs.MqttMessageHandlerStrategy;
import top.frsf.mqtt.session.SessionManager;

/**
 * MQTT协议事件 - 连接事件处理器
 *
 * @author He Kuntao
 * @since 2025/5/29 14:12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ConnectMessageHandler implements MqttMessageHandlerStrategy {

    private final SessionManager sessionManager;

    @Override
    public void handle(ChannelHandlerContext ctx, MqttMessage message) {
        MqttConnectMessage msg = (MqttConnectMessage) message;
        String clientId = msg.payload().clientIdentifier();
        log.info("Client connected: {}", clientId);

        // 简单验证客户端ID
        if (clientId == null || clientId.isEmpty()) {
            ctx.close();
            return;
        }

        // 存储客户端连接
        sessionManager.addClient(clientId, (NioSocketChannel) ctx.channel());

        // 返回连接成功
        ctx.writeAndFlush(createConnAck());
    }

    @Override
    public MqttMessageType supportedType() {
        return MqttMessageType.CONNECT;
    }
}
